<template>
  <div>
    <page :asideShow="asideShow" :footShow="footShow">
      <div slot="toolbar">
        <el-form :inline="true" :model="filters" label-position="right">
          <el-form-item label="选择小区">
            <el-select
              v-model="filters.CID"
              filterable
              placeholder="请选择"
              @keydown.enter.native="handleQuery('a')"
              clearable
            >
              <el-option
                v-for="item in getCommunity"
                :key="item.CID"
                :label="item.name"
                :value="item.CID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="filters.Status"
              filterable
              placeholder="请选择"
              @keydown.enter.native="handleQuery('a')"
              clearable
            >
              <el-option
                v-for="item in getStatus"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="进出类型">
            <el-select
              v-model="filters.equipment"
              filterable
              placeholder="请选择"
              @keydown.enter.native="refreshPageRequest(1)"
              @change="refreshPageRequest(1)"
              clearable
            >
              <el-option
                v-for="item in sblist"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="起始时间：">
            <el-date-picker
              class="normal"
              v-model="filters.startTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间：">
            <el-date-picker
              class="normal"
              v-model="filters.endTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div slot="btnSearch">
        <el-button type="primary" @click="handleQuery('a')">查询</el-button>
        <el-button type="primary" @click="handleAdd" v-show="hasPerm('resource:addequipment:add')">新增</el-button>
      </div>
      <div slot="content">
        <el-table
          :header-cell-style="{ background: '#e7eaf0', color: '#606266' }"
          :data="pageResult"
          stripe
          v-loading="loading"
          style="width: 100%"
          element-loading-text="加载中..."
          v-if="footShow == true"
        >
          <el-table-column
            prop="area_name"
            header-align="center"
            align="center"
            label="小区名称"
          ></el-table-column>
          <el-table-column prop="sn" header-align="center" align="center" label="设备ID"></el-table-column>
          <el-table-column prop="name" header-align="center" align="center" label="进出口"></el-table-column>
          <el-table-column prop="device_type" header-align="center" align="center" label="平台名称 ">
            <template slot-scope="scope">
              <span v-if="scope.row.device_type == 2">Alink</span>
              <span v-if="scope.row.device_type == 1">SenseLink</span>
              <span v-if="scope.row.device_type == 3">云曜</span>
            </template>
          </el-table-column>
          <el-table-column prop="location" header-align="center" align="center" label="设备位置"></el-table-column>
          <el-table-column prop="last_offline_time" header-align="center" align="center" label="最后在线时间">
            <template slot-scope="scope">
              <span v-if="scope.row.last_offline_time">
                {{ $format(scope.row.last_offline_time) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="version" header-align="center" align="center" label="设备版本"></el-table-column>
          <el-table-column prop="status" header-align="center" align="center" label="状态">
            <template slot-scope="scope">
              <span v-if="scope.row.status == 1">在线</span>
              <span v-if="scope.row.status == 2">离线</span>
            </template>
          </el-table-column>
          <el-table-column prop="Status" header-align="center" align="center" label="操作" width="350">
            <template slot-scope="scope">
              <el-button
                type="success"
                @click="openDoorOne(scope.row)"
                :disabled="scope.row.status !== 1"
                v-show="hasPerm('resource:addequipment:close')"
                size="mini"
              >
                一键开门
              </el-button>
              <el-button
                v-if="scope.row.open == 1 && scope.row.device_type != 3"
                type="warning"
                @click="setRemote(scope.row, '2')"
                v-show="hasPerm('resource:addequipment:close')"
                size="mini"
              >
                开启远程关门
              </el-button>
              <el-button
                v-if="scope.row.open != 1 && scope.row.device_type != 3"
                type="primary"
                @click="setRemote(scope.row, '1')"
                size="mini"
                v-show="hasPerm('resource:addequipment:close')"
              >
                关闭远程开门
              </el-button>
              <el-button
                v-if="scope.row.device_type != 3"
                size="mini"
                type="primary"
                @click="getstateList(scope.row)"
                v-show="hasPerm('resource:addequipment:show')"
              >
                查看
              </el-button>
              <el-button
                v-if="scope.row.device_type == 3"
                size="mini"
                type="primary"
                @click="deleteOne(scope.row)"
                v-show="hasPerm('aged:device:remove')"
              >
                解绑
              </el-button>
              <el-button
                v-if="scope.row.device_type != 3"
                size="mini"
                type="warning"
                @click="editInfo(scope.row)"
                v-show="hasPerm('sys:menu:see')"
              >
                坐标编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <addequ v-if="footShow == false" @retList="retList" @closeAddequ="closeAddequ"></addequ>
      </div>
      <div slot="footer">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          @current-change="refreshPageRequest"
          :current-page="pageRequest.page"
          :page-size="pageRequest.limit"
          :total="totalSize"
          style="float: right"
        ></el-pagination>
      </div>
    </page>
    <!-- 详情弹框 -->
    <el-dialog
      class="dialog-container"
      title="状态详情"
      :visible.sync="dialogVisible"
      :modal-append-to-body="false"
    >
      <div class="record">
        <el-table
          :header-cell-style="{}"
          :data="dialogData"
          v-loading="loading"
          style="width: 100%"
          element-loading-text="加载中..."
          row-class-name
          cell-class-name
        >
          <el-table-column prop="type" label="设备状态" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.type === 1 ? '登录在线' : '通知离线' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="time" label="时间" align="center">
            <template slot-scope="scope">
              <span>{{ $format(scope.row.time) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer">
        <el-pagination
          layout="prev, pager, next"
          @current-change="refreshPageRequest1"
          :current-page="pageRequest1.page"
          :page-size="pageRequest1.limit"
          :total="totalSize1"
          style="float: right"
        ></el-pagination>
      </div>
    </el-dialog>
    <!-- 设备坐标位置编辑 -->
    <el-dialog
      class="dialog-container"
      title="设备坐标编辑"
      :visible.sync="isShowEdit"
      :modal-append-to-body="false"
    >
      <edit
        v-if="isShowEdit"
        :formData="currentRow"
        @editSuccess="editSuccess"
        @editClose="isShowEdit = false"
      ></edit>
    </el-dialog>
  </div>
</template>

<script>
import addequ from './comment/addequ';
import Edit from './comment/edit';
export default {
  components: {
    addequ,
    Edit
  },
  data() {
    return {
      isShowEdit: false, // 是否展示编辑界面
      sblist: [
        { label: '出', value: '1' },
        { label: '进', value: '2' }
      ],
      footShow: true,
      asideShow: false,
      viewVisible: false,
      dialogData: [], // 详情数据
      pageResult: [],
      selections: [],
      dataFormView: [],
      filters: {
        CID: '',
        startTime: '',
        endTime: '',
        Status: ''
      },
      startTime: '',
      endTime: '',
      pageRequest: {
        page: 1,
        limit: 10
      },
      pageRequest1: {
        page: 1,
        limit: 10
      },
      currentRow: null,
      columns: [],
      loading: false,
      totalSize: 0,
      totalSize1: 0,
      options: [
        {
          value: true,
          label: '在线'
        },
        {
          value: false,
          label: '离线'
        }
      ],
      // 新增编辑界面是否显示
      dialogVisible: false,
      getCommunity: [],
      getStatus: [
        {
          value: 1,
          name: '在线'
        },
        {
          value: 2,
          name: '离线'
        }
      ]
    };
  },
  methods: {
    //解绑设备
    deleteOne(e) {
      e.operation = 0;
      this.$confirm('确认提交吗？', '提示', {}).then(() => {
        this.loading = true;
        this.$api.wxNotic.DelData(e).then(res => {
          this.loading = false;
          if (res.code == 0) {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.handleQuery();
          } else {
            this.$message({
              message: '操作失败, ' + res.msg,
              type: 'error'
            });
          }
        });
      });
    },

    // 编辑完成
    editSuccess() {
      this.isShowEdit = false;
      this.handleQuery();
    },
    editInfo(e) {
      this.currentRow = e;
      this.isShowEdit = true;
    },
    retList() {
      this.handleQuery();
    },
    closeAddequ() {
      this.footShow = true;
      this.handleQuery();
    },
    setRemote(e, i) {
      let txt = '是否关闭远程开门？';
      if (i == 2) {
        txt = '是否开启远程开门？';
      }
      this.$confirm(txt, '提示', {}).then(() => {
        this.loading = true;
        const params = Object.assign(e, {});
        params.open = i;
        this.$api.resource.open_door_control(params).then(res => {
          this.loading = false;
          if (res.code == 0) {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.handleQuery();
          } else {
            this.$message({
              message: '操作失败, ' + res.msg,
              type: 'error'
            });
          }
        });
      });
    },
    // 获取分页数据
    handleQuery: function(val) {
      this.footShow = true;
      this.loading = true;
      let params = Object.assign(this.filters, {
        page: val ? '' : this.pageRequest.page,
        limit: val ? '' : this.pageRequest.limit
        // CID: this.filters.CID,
        // status: this.filters.Status
      });
      // params = {
      //   page: val ? "" : this.pageRequest.page,
      //   limit: val ? "" : this.pageRequest.limit,
      //   // startTime: this.startTime,
      //   // endTime: this.endTime,
      //   CID: this.filters.CID,
      //   status: this.filters.Status
      // };
      let paramJson = JSON.stringify(params);
      this.$api.resource.finddetailPage(paramJson).then(res => {
        this.loading = false;
        if (res.code == 0) {
          this.pageResult = res.data;
          this.totalSize = res.count;
          this.pageResult.map(item => {
            item.Time = this.$format(item.Time);
            // if (item.Status) {
            //   item.Status = "在线";
            // } else {
            //   item.Status = "离线";
            // }
          });
        } else {
          this.$message({ message: '操作失败, ' + res.msg, type: 'error' });
        }
      });
    },
    //获取设备状态
    getstateList(row) {
      // 显示弹框
      this.dialogVisible = true;
      // 调用接口
      let params = {};
      // if (row && row.LDID) {
      //   this.currentRow = row.LDID;
      // }
      params = {
        page: this.pageRequest1.page,
        limit: this.pageRequest1.limit,
        sn: row.sn
      };
      let param = JSON.stringify(params);
      this.loading = true;
      this.$api.wxNotic.sys_device_log(params).then(res => {
        if (res.code == 0) {
          this.loading = false;
          this.totalSize1 = res.count;
          if (res.data) {
            this.dialogData = res.data;
          } else {
            this.dialogData = [];
          }
        } else {
          this.$message({ message: '操作失败, ' + res.msg, type: 'error' });
        }
      });
    },
    //获取小区的列表选择器
    getCommunityList() {
      let params = {};
      params = {
        where: {
          CODES: []
        }
      };
      let param = JSON.stringify(params);
      this.loading = true;
      this.$api.three.communityList(params).then(res => {
        if (res.code == 0) {
          this.loading = false;
          this.getCommunity = res.data;
        } else {
          this.$message({ message: '操作失败, ' + res.msg, type: 'error' });
        }
      });
    },

    // 显示新增界面
    handleAdd: function() {
      this.footShow = false;
      this.operation = true;
      this.dataForm = {
        dType: '',
        dValue: '',
        describe: ''
      };
    },
    // 显示编辑界面
    handleEdit: function(params) {
      this.viewVisible = true;
      // this.operation = false;
      this.dataFormView = params;
    },
    //删除
    handleDelete(row) {
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        let params = {
          DID: row.DID
        };

        var paramJson = JSON.stringify(params);
        this.$api.dict.batchDelete(paramJson).then(res => {
          if (res.code == 0) {
            this.handleQuery();
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          } else {
            this.$message({
              message: '操作失败, ' + res.msg,
              type: 'error'
            });
          }
        });
      });
    },
    // 批量删除
    batchDelete() {
      this.$confirm('确认删除选中用户吗？', '提示', 'warning').then(() => {
        let selLength = this.selections.length;
        let totalLength = this.pageResult.length;
        let isReduce = selLength == totalLength ? true : false;
        let params = this.selections
          .map(item => {
            return item.DID;
          })
          .join(',');
        this.$api.dict
          .batchDelete({
            DID: params
          })
          .then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功');
              if (isReduce) {
                this.pageRequest.page--;
              }
              this.handleQuery();
            } else {
              this.$message.error(res.msg);
            }
          });
      });
    },
    // 编辑
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            let params = Object.assign(this.dataForm);
            let paramJson = JSON.stringify(params);
            this.$api.dict.save(paramJson).then(res => {
              this.editLoading = false;
              if (res.code == 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.$refs['dataForm'].resetFields();
              } else {
                this.$message({
                  message: '操作失败, ' + res.msg,
                  type: 'error'
                });
              }
              this.handleQuery(null);
            });
          });
        }
      });
    },
    openDoorOne(item) {
      console.log(item);
      const userinfo = JSON.parse(sessionStorage.getItem('userInfo'));
      console.log(userinfo);
      let param = {
        CID: item.CID,
        userID: userinfo._id,
        id: item.sn
      };
      this.$confirm('是否开门?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$api.wxJob.senseLink_open_door(param).then(res => {
            if (res.data.code == 0) {
              this.$message({
                type: 'success',
                message: '开门成功!'
              });
            } else {
              this.$message({
                type: 'error',
                message: '开门失败！'
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '开门失败！'
          });
        });
    },
    refreshPageRequest(page) {
      this.pageRequest.page = page;
      this.handleQuery();
    },

    refreshPageRequest1(page) {
      this.pageRequest1.page = page;
      this.getstateList();
    },
    handleSelectionChange(val) {
      this.selections = val;
    }
  },
  mounted() {
    this.filters.CID = localStorage.getItem('home_CID');
    this.handleQuery();
    this.getCommunityList();
  }
};
</script>

<style></style>
